﻿namespace SaveALot.DepartmentTaskTracking
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Workflow.Activities;
    using System.Workflow.ComponentModel;

    using Microsoft.SharePoint;

    public partial class TaskTracking : SequenceActivity
    {
        #region Fields

        public static DependencyProperty CurrentUrlProperty = DependencyProperty.Register
              ( "CurrentUrl", typeof( string ), typeof( TaskTracking ) );
        public static DependencyProperty StoreIDProperty = DependencyProperty.Register
          ( "StoreID", typeof( string ), typeof( TaskTracking ) );
        public static DependencyProperty StoreUrlProperty = DependencyProperty.Register
          ( "StoreUrl", typeof( string ), typeof( TaskTracking ) );

        #endregion Fields

        #region Constructors

        public TaskTracking( )
        {
            InitializeComponent( );
        }

        #endregion Constructors

        #region Properties

        [Category( "Custom Save-A-Lot Actions" ),
        Browsable( true )]
        [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible )]
        public string CurrentUrl
        {
            get
            {
                return ( ( string )
                    ( base.GetValue( TaskTracking.CurrentUrlProperty ) ) );
            }
            set
            {
                base.SetValue( TaskTracking.CurrentUrlProperty, value );
            }
        }

        [Category( "Custom Save-A-Lot Actions" ),
        Browsable( true )]
        [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible )]
        public string StoreID
        {
            get
            {
                return ( ( string )
                    ( base.GetValue( TaskTracking.StoreIDProperty ) ) );
            }
            set
            {
                base.SetValue( TaskTracking.StoreIDProperty, value );
            }
        }

        [Category( "Custom Save-A-Lot Actions" ),
        Browsable( true )]
        [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible )]
        public string StoreUrl
        {
            get
            {
                return ( ( string )
                    ( base.GetValue( TaskTracking.StoreUrlProperty ) ) );
            }
            set
            {
                base.SetValue( TaskTracking.StoreUrlProperty, value );
            }
        }

        #endregion Properties

        #region Methods

        protected override ActivityExecutionStatus Execute( ActivityExecutionContext executionContext )
        {
            try
            {
                using ( SPSite site = new SPSite( StoreUrl ) )
                {
                    site.AllowUnsafeUpdates = true;
                    using ( SPWeb web = site.OpenWeb( ) )
                    {
                        web.AllowUnsafeUpdates = true;

                        SPSecurity.RunWithElevatedPrivileges( delegate( )
                        {
                            using ( SPSite storeSite = new SPSite( site.ID ) )
                            {
                                storeSite.AllowUnsafeUpdates = true;

                                using ( SPWeb storeWeb = site.OpenWeb( web.ID ) )
                                {
                                    storeWeb.AllowUnsafeUpdates = true;

                                    SPList activeTaskList = storeWeb.Lists[ "Stores and Tasks" ];

                                    //grid tracking
                                    SPList currentDepartmentList = storeWeb.Lists[ CurrentUrl ];
                                    SPFieldCollection deparmentColumns = currentDepartmentList.Fields;

                                    //Get the tasks for the store from Store and Tasks...
                                    SPQuery tasksQuery = new SPQuery( );
                                    tasksQuery.Query = string.Format( "<Where><Eq><FieldRef Name='Store_x0020_Record_x0020_ID' /><Value Type='Number'>{0}</Value></Eq></Where>", StoreID.Trim( ) );

                                    SPListItemCollection taskRecords = activeTaskList.GetItems( tasksQuery );

                                    //Get the current department list item for the store...
                                    SPQuery departmentQuery = new SPQuery( );
                                    if ( CurrentUrl.Trim( ).Equals( "Stores Detail" ) )
                                        departmentQuery.Query = string.Format( "<Where><Eq><FieldRef Name='Reference_x0020__x0023_' /><Value Type='Number'>{0}</Value></Eq></Where>", StoreID.Trim( ) );
                                    else
                                        departmentQuery.Query = string.Format( "<Where><Eq><FieldRef Name='Store_x0020_Reference_x0020_ID' /><Value Type='Number'>{0}</Value></Eq></Where>", StoreID.Trim( ) );

                                    SPListItemCollection departmentList = currentDepartmentList.GetItems( departmentQuery );

                                    SPListItem currentListItem = departmentList[ 0 ];
                                    foreach ( SPField field in deparmentColumns )
                                    {
                                        SPFieldType type = field.Type;

                                        if ( type == SPFieldType.DateTime &&
                                            currentListItem[ field.InternalName ] != null )
                                        {
                                            if ( !string.IsNullOrEmpty( currentListItem[ field.InternalName ].ToString( ) ) &&
                                                field.Hidden == false &&
                                                field.CanBeDeleted == true )
                                            {
                                                //Loop through tasks in taskRecords and update the Task Status of the task where Task Description == field.Tite.
                                                foreach ( SPListItem taskItem in taskRecords )
                                                {
                                                    if ( taskItem[ "Task Description" ].ToString( ).Trim( ).Equals( field.Title.ToString( ).Trim( ), StringComparison.OrdinalIgnoreCase ) &&
                                                        taskItem[ "Task Status" ].ToString( ) != "Completed" )
                                                    {
                                                        taskItem[ "Completed Date" ] = DateTime.Parse( currentListItem[ field.InternalName ].ToString( ) ).ToShortDateString( );
                                                        taskItem[ "Task Status" ] = activeTaskList.Fields[ "Task Status" ].GetFieldValue( "Completed" );
                                                        taskItem.Update( );
                                                        activeTaskList.Update( );
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } );
                    }
                }
            }
            catch ( Exception ex )
            {
                EventLog.WriteEntry( "Department Task Tracking Workflow", ex.ToString( ) );
            }

            return ActivityExecutionStatus.Closed;
        }

        #endregion Methods
    }
}